import { login, checkUsernamePassword, logout, getTokenInfo, selUserAll, 
  selUserByUsername, addUser, updateUser, delUser, updateMyPwd } from '@/services/user';
import { errNotification, successNotification } from '@/utils/notification';
import { getData, setData, removeData } from '@/utils/localData';
import router from 'umi/router';

export default {
    namespace: 'user',
  
    state: {
      loginIsOk: false, //需要短信验证时 用户名密码是否验证成功
      sendSmsKey: '', //需要短信验证时 发短信用的临时码
      errMsg: false, //登录错误信息
      userList: [],
      userListPage: 1,
      userListTotal: 0,
      list: [],
      currentUser: {},
      upAddInfo:{ //修改添加对话框信息
        title: "", //标题
        visible: false, //可见
        action: false, //要提交的action 新增或更新
        isUpdate: false, //是否更新了表单数据
        //表单数据
        id: null, 
        username: null,
        password: null,
        phone: null,
        roleList:[]
      }
    },
  
    effects: {
      *fetchSelUserAll(param, { call, put }) { //查询全部用户
        const response = yield call(selUserAll, param);
        if(response.success){
          yield put({
            type: 'selUserAll',
            payload: response.data,
          });
        }
      },
      *fetchAddUser(param, { call, put }) { //添加用户
        const selSameRs = yield call(selUserByUsername, param)
        if(selSameRs.success){
          const response = yield call(addUser, param);
          if(!response.success){
            errNotification("用户添加失败","")
          }
          successNotification("用户添加成功","")
          param.payload.username = null
          param.payload.phone = null
          const response2 = yield call(selUserAll, param);
          if(response2.success){
            yield put({
              type: 'selUserAll',
              payload: response2.data,
            });
          }
        }else{
          errNotification("用户名重复","")
        }
      },
      *fetchUpdateUser(param, { call, put }) { //修改用户
        const response = yield call(updateUser, param);
        param.payload.username = null
        param.payload.phone = null
        if(response.success){
          successNotification("用户修改成功","")
          const response2 = yield call(selUserAll, param);
          if(response2.success){
            yield put({
              type: 'selUserAll',
              payload: response2.data,
            });
          }
        }else{
          errNotification("用户修改失败","")
        }
      },
      *fetchDelUser(param, { call, put }) { //删除用户
        const response = yield call(delUser, param);
        if(response.success && response.data.count === 1){
          successNotification("用户删除成功","")
          const response2 = yield call(selUserAll, param);
          if(response2.success){
            yield put({
              type: 'selUserAll',
              payload: response2.data,
            });
          }
        }else{
          errNotification("用户删除失败","")
        }
      },
      *fetchTokenInfo(param, { call }) {
        const response = yield call(getTokenInfo, param);
        if(response.success){
          setData("userId", response.data.userId)
          setData("username", response.data.username)
          setData("myAuthorized", response.data.authorities)
        }
      },
      *fetchLogin(param, { call, put }) {
        console.log("login-model=================")
        const response = yield call(login, param);
        let errMsg = false
        console.log("login-rs=================",response)
        if(response.success){
          setData("token", response.data.access_token)
          setData("refreshToken", response.data.refresh_token)
          //获取用户的权限及用户基本信息
          const response2 = yield call(getTokenInfo, param);
          if(response2.success){
            setData("userId", response2.data.userId)
            setData("username", response2.data.username)
            setData("myAuthorized", response2.data.authorities)
          }else{
            errMsg = "获取用户信息失败"
          }
          yield put({
            type: 'setCheckUsernamePassword',
            payload: {
              loginIsOk: false,
              sendSmsKey: ''
            },
          });
        }else{
          errMsg = response.subMsg
        }
        if(errMsg){
          yield put({
            type: 'login',
            payload: {errMsg: errMsg},
          });
        }else{
          router.push("/")
        }
        
      },
      *fetchUpdateMyPwd(param, { call, put }) {
        const response = yield call(updateMyPwd, param);
        if(response.success){          
          removeData("refreshToken")
          removeData("token")
          router.push("/login")
        }else{
          errNotification("用户删除失败",response.subMsg)
        }
      },
      *fetchCheckUsernamePassword(param, { call, put }) {
        const response = yield call(checkUsernamePassword, param);
        if(response.success){
          yield put({
            type: 'setCheckUsernamePassword',
            payload: {
              loginIsOk: true,
              sendSmsKey: response.data
            },
          });
        }else{
          yield put({
            type: 'login',
            payload: {errMsg: response.subMsg},
          });
        }
      },
      *fetchLogout(param, { call, put }) {
        const response = yield call(logout, param);
        removeData("refreshToken")
        removeData("token")
        router.push("/login")
      },
    },
  
    reducers: {
      selUserAll(state, action) {
        if(action.payload.list){
          action.payload.list.map((item,index)=>{
            item.key = index
          })
        }
        return {
          ...state,
          userList: action.payload.list,
          userListPage: action.payload.pageNum,
          userListTotal: action.payload.total    
        };
      },
      login(state, action) {
        return {
          ...state,
          errMsg: action.payload.errMsg,
        };
      },
      setCheckUsernamePassword(state, action) {
        return {
          ...state,
          loginIsOk: action.payload.loginIsOk,
          sendSmsKey: action.payload.sendSmsKey
        };
      },
      setUpAddInfo(state, action) {
        return {
          ...state,
          upAddInfo: action.payload           
        };
      },
      changeNotifyCount(state, action) {
        return {
          ...state,
          currentUser: {
            ...state.currentUser,
            notifyCount: action.payload.totalCount,
            unreadCount: action.payload.unreadCount,
          },
        };
      },
    },
  };